package com.travel.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.travel.entity.Scenic;
import com.travel.entity.ScenicFavorite;
import com.travel.service.ScenicFavoriteService;
import com.travel.service.ScenicService;
import com.travel.service.impl.ScenicFavoriteServiceImpl;
import com.travel.service.impl.ScenicServiceImpl;
import com.travel.util.PageInfo;

/**
 * Servlet implementation class ScenicServlet
 */
@WebServlet("/scenic")
@MultipartConfig
public class ScenicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private ScenicService scenicService = new ScenicServiceImpl();
    private ScenicFavoriteService scenicFavoriteService=new ScenicFavoriteServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ScenicServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String op = request.getParameter("op");
		if(op == null) {
			//查询列表
			doFindScenic(request,response);
		}else if ("delete".equals(op)) {
			//删除功能
			doDeleteById(request,response);
		}else if ("searchByScenicName".equals(op)) {
			//搜索功能
			doSearchByScenicName(request,response);
		}else if ("searchByPage".equals(op)) {
			//分页查询列表
			doFindScenicByPage(request,response);
		}else if ("getScenicById".equals(op)) {
			//通过景点编号进行查询
			doGetScenicById(request,response);
		}else if("modify".equals(op)) {
			// 修改
			doModify(request, response);
			
		}else if("insertScenic".equals(op)) {
			//发布景点信息
			doInsert(request,response);
		}else if ("existOfScenicName".equals(op)) {
			// 通过景点名称判断景点存在
			doExistOfScenicName(request,response);
		}else if ("insertGallery".equals(op)) {
			//收藏景点
			doScenicGallery(request,response);
		}
	}

	

	private void doScenicGallery(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int scenicId=Integer.parseInt(request.getParameter("scenicId"));
		int userId=Integer.parseInt(request.getParameter("userId"));
		
		List<ScenicFavorite> findbyUserId = scenicFavoriteService.findbyUserId(userId, scenicId);
		System.out.println(findbyUserId);
		if (findbyUserId.size()==0) {
			ScenicFavorite scenicFavorite=new ScenicFavorite(null, userId, scenicId);
			boolean insert = scenicFavoriteService.insert(scenicFavorite);
			if (insert) {
				response.getWriter().print("success");
			}
		}else {
			System.out.println(2);
			response.getWriter().print("fail");
		}

	}

	private void doExistOfScenicName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调用业务层
		String scenicName = request.getParameter("scenicName");
		List<Scenic> list = scenicService.getScenicByScenicName(scenicName);
		if (list.isEmpty()) { // 空
			// 用户名不存在
			// 响应文本数据
			response.getWriter().print("no exist"); // 不存在
		} else {
           // 用户名存在
		   // 响应文本数据
		   response.getWriter().print("exist"); // 存在
		}
	}

	private void doInsert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String scenicName = request.getParameter("scenicName");
		String scenicDesc = request.getParameter("scenicDesc");
		String scenicPrice = request.getParameter("scenicPrice");
		BigDecimal bigDecimal = new BigDecimal(scenicPrice);
		
		// 获取单个文件
		Part part = request.getPart("scenicPicture");
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			// 调用业务层
			scenicService.insertScenic(new Scenic(null, scenicName, scenicDesc, null, bigDecimal));
		} else {
			// 有上传
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
				response.sendRedirect("front/register.jsp?fileuploaderror=notallowtype");
				return;
			}else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				// 保证文件名唯一
				// 时间戳
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				// 4位随机数
				int random = (int)((Math.random()*9+1)*1000);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);
				
				// 定义文件存储目录
				File file = new File("D:\\image\\scenic");
				
				StringBuffer filePath = new StringBuffer();
				
				filePath.append(file.getPath()).append(File.separator).append(fileName);
				
				// 将文件写入指定位置
				part.write(filePath.toString());
				
				// 调用业务逻辑层
				scenicService.insertScenic(new Scenic(null, scenicName, scenicDesc, fileName.toString(), bigDecimal));
				}
			}
		
			// 跳转到前台首页
			response.sendRedirect("back/findAllScenic.jsp");
		
	}

	private void doGetScenicById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int getScenicById = Integer.parseInt(request.getParameter("scenicId"));
		Scenic scenic = scenicService.getByScenicId(getScenicById);
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(scenic);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter  out= response.getWriter();
	    out.print(json);
	}

	private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		int scenicId = Integer.parseInt(request.getParameter("scenicid"));
		String scenicName = request.getParameter("scenicname");
		String scenicDesc = request.getParameter("scenicdesc");
		//String scenicPicture = request.getParameter("scenicpicture");
		String scenicPrice = request.getParameter("scenicprice");
		BigDecimal scenicPrice1 = new BigDecimal(scenicPrice);
		
		// 获取单个文件
		Part part = request.getPart("scenicpicture");
				
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			// 调用业务层 编辑hotel
			Scenic scenic = new Scenic(scenicId, scenicName, scenicDesc, null, scenicPrice1);
			boolean updateScenic = scenicService.updateScenic(scenic);
			if (updateScenic) {
			    // 响应数据
			    PrintWriter  out= response.getWriter();
			    out.print("success");
			}
		} else {
			// 有上传酒店的图片
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
				return;
			}else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				System.out.println(realFileName);
				// 定义文件存储目录
				File file = new File("D:\\image\\scenic");
						
			
				StringBuffer filePath = new StringBuffer();
						
				filePath.append(file.getPath()).append(File.separator).append(realFileName);
				System.out.println(filePath);
				// 将文件写入指定位置
				part.write(filePath.toString());
						
				// 调用业务逻辑层
		
				Scenic scenic = new Scenic(scenicId, scenicName, scenicDesc, realFileName, scenicPrice1);
				boolean modify = scenicService.updateScenic(scenic);
				 //response.setContentType("application/x-www-form-urlencoded;charset=utf-8");
				if (modify) {
				    // 响应数据
				    PrintWriter out= response.getWriter();
				    out.print("success");
				}
			}
		}
	}

	private void doFindScenicByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		String scenicName = request.getParameter("keyword");
		
		PageInfo<Scenic> pageInfo = scenicService.findByPage(pageNum, pageSize, scenicName);
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(pageInfo);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter  out= response.getWriter();
		out.print(json);
	}

	private void doSearchByScenicName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String scenicName = request.getParameter("scenicName");
		List<Scenic> byScenicName = scenicService.getByScenicName(scenicName);
		if (byScenicName.isEmpty()) { // 空
			// 景点不存在
			// 响应文本数据
			response.getWriter().print("success"); // 不存在
		} else {
           // 景点存在
		   // 响应文本数据
		   response.getWriter().print("error"); // 存在
		}
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(byScenicName);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter  out= response.getWriter();
		out.print(json);
	}

	private void doDeleteById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String scenicId = request.getParameter("scenicId");
		scenicService.deleteId(Integer.parseInt(scenicId));
		doFindScenicByPage(request,response);
		
		
	}

	private void doFindScenic(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//调用业务层
		List<Scenic> list = scenicService.find();
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(list);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter  out= response.getWriter();
		out.print(json);
	}

}
